var salt = sessionStorage.getItem('usersalt');
layui.config({
    base: '../../../js/',
})
var id = getQueryVariable('id');
var detail = getQueryVariable('detail');
var edit = getQueryVariable('edit');
var editCompanyId;

if (id) {
    $.post(url + 'questionPaper/getInfo', {id: id, Token: salt}, function (data) {
        if (data.code == 0) {
            var data = data.data;
            $("#title").val(data.title);
            $("#examType").val(data.examType);
            $("#duration").val(data.duration);
            if (data.startTime) {
                layui.use(['laydate'], function () {
                    var laydate = layui.laydate;
                    laydate.render({
                        elem: '#startTime',
                        value: new Date(data.startTime)
                    });
                    laydate.render({
                        elem: '#endTime',
                        value: new Date(data.endTime)
                    });
                })
            } else {
                sessionStorage.setItem("outTime", true);
            }
            $("#radio").val(data.radio);
            $("#multiSelect").val(data.multiSelect);
            $("#tfng").val(data.tfng);
            $("#entId").val(data.entName);
            initTime()
            editCompanyId = data.entId;
            if(sessionStorage.getItem("edit")){
                return
            }
            $(".radio_num").text(data.radioQuestion.length);
            $(".multiSelect_num").text(data.multiSelectQuestion.length);
            $(".tfng_num").text(data.tfngQuestion.length);
            var total = data.radioQuestion.length + data.multiSelectQuestion.length + data.tfngQuestion.length;
            var typeArr = [data.radioQuestion.length, data.multiSelectQuestion.length, data.tfngQuestion.length];
            sessionStorage.setItem("typeArr", typeArr);
            var choiceArr = [];
            //设置题目
            data.radioQuestion.forEach(function (item) {
                choiceArr.push(item.id)
            });
            data.multiSelectQuestion.forEach(function (item) {
                choiceArr.push(item.id)
            });
            data.tfngQuestion.forEach(function (item) {
                choiceArr.push(item.id)
            });
            sessionStorage.setItem("choiceArr", choiceArr);
            $(".red_box p").text("试题数：共" + total + "道题目");


        } else {
            alert(data.msg)
        }
    })
    if (detail) {
        $(".add,.submit").remove();
    }
} else {
    initTime()
    $("#entId").val(sessionStorage.getItem("entName"));
    editCompanyId = sessionStorage.getItem("entId");
}
layui.use(['form', 'layer', 'laydate', 'table', 'multiSelect'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        formSelects = layui.formSelects,
        table = layui.table;

    /*验证登录*/
    if (!sessionStorage.getItem('username')) {
        layer.msg('请先登录');
        setTimeout("top.location.href='../../../index.html'", 1000);
    }

    /*时间选择器*/
    laydate.render({
        elem: '#startTime',
        trigger: 'click'
    });

    laydate.render({
        elem: '#endTime',
        trigger: 'click'
    });
    form.render();

    /*筛选*/
    $('#seleCheck').on('click', function () {

    });

    /*搜索*/
    $('#findscri').on('click', function () {
        var inptext = $('#inptext').val();
        var box = /\s/g;
        var param = inptext.replace(box, '');
    });
    var company;
    /*取出所有的单位*/
    function getAllDanwei() {
        $.ajax({
            url: url + 'baseEnt/getAllEnt',
            dataType: 'json',
            async: false,
            type: "POST",
            data: {},
            success: function (data) {
                $('#danwei').empty();
                if (data.code == 0) {
                    var list = data.data;
                    company = list;
                }

            },
            error: function (error) {
                console.log("获取失败");
            }
        });
    }

    getAllDanwei();

    var setting = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: zTreeOnCheck
        }
    };
    var zNodes = company;
    $.fn.zTree.init($("#danwei"), setting, zNodes);

    function getSydwVal() {
        var treeArr = [];
        var treeObj = $.fn.zTree.getZTreeObj("danwei");
        var nodes = treeObj.getCheckedNodes(true);
        for (var i = 0; i < nodes.length; i++) {
            treeArr.push(nodes[i].id); //获取选中节点的值
        }
        return treeArr;
    }

    $('#entId').click(function () {
        $('#danwei').show();
    });

    function zTreeOnCheck(event, treeId, treeNode) {
        var nval = "";
        var treeObj = $.fn.zTree.getZTreeObj("danwei");
        var nodes = treeObj.getCheckedNodes(true);
        for (var i = 0; i < nodes.length; i++) {
            nval += nodes[i].name + ",";
        }
        $('#entId').val(nval.substr(0, nval.length - 1));
    };
    /*------------tree.end------------*/

    var tableIns;

    //新增
    $(".addNews_btn").click(function () {
        $(".model").show();
    });


    //题库
    $(".subject_btn").click(function () {
        location.href = "../subject/subject.html"

    });

    //导出
    $(".export_btn").click(function () {

    });
    //导入
    $(".import_btn").click(function () {
        layer.open({
            type: 2,
            title: false,
            content: "page/404.html",
            area: ['700px', '300px']
        });
    });

    $("body").on("click", ".add,.red_box", function () {
        sessionStorage.setItem("entId", getSydwVal() ? getSydwVal().toString() : editCompanyId);
        sessionStorage.setItem("entName", $("#entId").val());
        if (edit) {
            location.href = "../subject/subject.html?test=true&edit=true";
        } else {
            location.href = "../subject/subject.html?test=true";
        }

    });

    $("body").on("click", ".submit", function () {
        var title = $("#title").val();
        var entId = getSydwVal().length > 0 ? getSydwVal().toString() : editCompanyId;
        var examType = $("#examType").val();
        var duration = $("#duration").val();
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();
        var radio = $("#radio").val();
        var multiSelect = $("#multiSelect").val();
        var tfng = $("#tfng").val();
        var sortType = $("#sortType").val();
        var qusetionId = sessionStorage.getItem("choiceArr");
        var outTime = $(".outTime").hasClass("active");
        if (!title || !entId || !examType || !duration || !sortType) {
            alert("请完善表单！");
            return
        }
        var reg = new RegExp("^[0-9]*[1-9][0-9]*$");
        if ($(".radio_num").text() > 0 && !radio) {
            alert("请填写单选题分值！");
            return
        } else if (radio && !reg.test(radio) && $(".radio_num").text() > 0) {
            alert("题目分值应为正整数");
            return
        }
        if ($(".multiSelect_num").text() > 0 && !multiSelect) {
            alert("请填写多选题分值！");
            return
        } else if (multiSelect && !reg.test(multiSelect) && $(".multiSelect_num").text() > 0) {
            alert("题目分值应为正整数");
            return
        }
        if ($(".tfng_num").text() > 0 && !tfng) {
            alert("请填写判断题分值！");
            return
        } else if (tfng && !reg.test(tfng) && $(".tfng_num").text() > 0) {
            alert("题目分值应为正整数");
            return
        }

        if (duration > 120 || isNaN(duration) || duration < 1) {
            alert("请输入正确的考试时间(1 ~ 120min)！");
            return
        }
        if (!outTime && (!startTime || !endTime)) {
            alert("请选择时间！");
            return
        }
        if (!qusetionId) {
            alert("请添加题目！");
            return
        }
        var sendData;
        if (id) {
            //编辑
            sendData = {
                title: title,
                entId: entId,
                examType: examType,
                duration: duration,
                startTime: outTime ? '' : startTime,
                endTime: outTime ? '' : endTime,
                radio: radio,
                multiSelect: multiSelect,
                tfng: tfng,
                sortType: sortType,
                qusetionId: qusetionId,
                Token: salt,
                id:id,
            }
            $.post(url + 'questionPaper/editQuestionPaper', sendData, function (data) {
                if (data.code == 0) {
                    layer.alert("编辑成功", {
                        btn: ['确定'] //按钮
                    }, function (index) {
                        layer.close(index);
                        sessionStorage.removeItem("choiceArr");
                        sessionStorage.removeItem("typeArr");
                        sessionStorage.removeItem("entName");
                        sessionStorage.removeItem("entId");
                        sessionStorage.removeItem("edit");
                        history.go(-1);
                    });
                } else {
                    alert(data.msg);
                }
            })
        }else{
            sendData = {
                title: title,
                entId: entId,
                examType: examType,
                duration: duration,
                startTime: outTime ? '' : startTime,
                endTime: outTime ? '' : endTime,
                radio: radio,
                multiSelect: multiSelect,
                tfng: tfng,
                sortType: sortType,
                qusetionId: qusetionId,
                Token: salt,
            }
            $.post(url + 'questionPaper/addQuestionPaper', sendData, function (data) {
                if (data.code == 0) {
                    layer.alert("新增成功", {
                        btn: ['确定'] //按钮
                    }, function (index) {
                        layer.close(index);
                        sessionStorage.removeItem("choiceArr");
                        sessionStorage.removeItem("typeArr");
                        sessionStorage.removeItem("entName");
                        sessionStorage.removeItem("entId");
                        sessionStorage.removeItem("edit");
                        history.go(-1);
                    });
                } else {
                    alert(data.msg);
                }
            })
        }
    })
})


function showDetail(checkId) {
    location.href = '../detail/detail.html?id=' + checkId;
}


initChoice()
function initChoice() {
    if (sessionStorage.getItem("choiceArr")) {
        console.log(sessionStorage.getItem("choiceArr"))
        var choiceArr = sessionStorage.getItem("choiceArr").split(",");
        var typeArr = sessionStorage.getItem("typeArr").split(",");
        $(".red_box p").text("试题数：共" + choiceArr.length + "道题目");
        $(".radio_num").text(typeArr[0]);
        $(".multiSelect_num").text(typeArr[1]);
        $(".tfng_num").text(typeArr[2])
    }

}

$("body").on("click", ".outTime", function () {
    $(this).toggleClass("active");
    $(this).hasClass("active") ? $("#startTime,#endTime").prop("disabled", true) : $("#startTime,#endTime").prop("disabled", false);
    $(this).hasClass("active") ? sessionStorage.setItem("outTime", true) : sessionStorage.removeItem("outTime");
})

$("body").on("click", ".back", function () {
    sessionStorage.removeItem('entId');
    sessionStorage.removeItem('entName');
    sessionStorage.removeItem("choiceArr");
    sessionStorage.removeItem("typeArr");
    sessionStorage.removeItem("outTime");
    history.go(-1);
})

function initTime() {
    if (sessionStorage.getItem("outTime")) {
        $(".outTime").addClass("active");
        $("#startTime,#endTime").prop("disabled", true);
    }
}

















